<template>
  <view class="listings-container">
    <!-- 搜索和筛选区域 -->
    <view class="search-filter-section">
      <view class="search-box">
        <input
          v-model="searchKeyword"
          placeholder="搜索公司名称"
          class="search-input"
          @confirm="handleSearch"
        />
        <button class="search-btn" @click="handleSearch">搜索</button>
        <button class="refresh-btn" @click="handleRefresh" :disabled="isLoading">
          <text class="refresh-icon">↻</text>
        </button>
      </view>
      
      <view class="filter-row">
        <picker
          :value="selectedTypeIndex"
          :range="listingTypes"
          @change="onTypeChange"
          class="filter-picker"
        >
          <view class="picker-text">{{ listingTypes[selectedTypeIndex] }}</view>
        </picker>

        <picker
          :value="selectedProvinceIndex"
          :range="provinces"
          @change="onProvinceChange"
          class="filter-picker"
        >
          <view class="picker-text">{{ provinces[selectedProvinceIndex] }}</view>
        </picker>

        <picker
          :value="selectedCityIndex"
          :range="cities"
          @change="onCityChange"
          class="filter-picker"
        >
          <view class="picker-text">{{ cities[selectedCityIndex] }}</view>
        </picker>
      </view>
    </view>

    <!-- 列表区域 -->
    <scroll-view
      class="listings-scroll"
      scroll-y
      @scrolltolower="loadMore"
      :enhanced="true"
      :bounces="false"
      :enable-back-to-top="true"
      :scroll-with-animation="true"
    >
      <view class="listings-list">
        <view 
          v-for="item in listings" 
          :key="item.id"
          class="listing-item"
          @click="goToDetail(item.id)"
        >
          <view class="listing-header">
            <text class="company-name">{{ item.company_name }}</text>
            <view class="status-tag" :class="getStatusClass(item.status)">
              {{ item.status }}
            </view>
          </view>
          
          <view class="listing-info">
            <view class="info-row">
              <text class="label">类型：</text>
              <text class="value">{{ item.listing_type }}</text>
            </view>
            <view class="info-row">
              <text class="label">地区：</text>
              <text class="value">{{ formatLocation(item) }}</text>
            </view>
            <view class="info-row">
              <text class="label">成立时间：</text>
              <text class="value">{{ formatDate(item.establishment_date) }}</text>
            </view>
            <view class="info-row">
              <text class="label">注册资本：</text>
              <text class="value">{{ item.registered_capital_range || '未填写' }}</text>
            </view>
          </view>
          
          <view class="listing-footer">
            <view class="price-section">
              <text v-if="item.is_negotiable" class="price negotiable">面议</text>
              <text v-else-if="item.price" class="price">¥{{ formatPrice(item.price) }}</text>
              <text v-else class="price negotiable">面议</text>
            </view>
            <text class="publish-time">{{ formatTime(item.created_at) }}</text>
          </view>
        </view>
      </view>
      
      <!-- 加载状态 -->
      <view class="loading-section" v-if="isLoading">
        <text class="loading-text">加载中...</text>
      </view>
      
      <!-- 没有更多数据 -->
      <view class="no-more-section" v-if="!hasMore && listings.length > 0">
        <text class="no-more-text">没有更多数据了</text>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-section" v-if="!isLoading && listings.length === 0">
        <text class="empty-text">暂无数据</text>
      </view>
    </scroll-view>

    <!-- 悬浮按钮 -->
    <view class="floating-buttons">
      <button class="floating-btn publish-btn" @click="goToPublish">
        <text class="btn-text">发布入库</text>
      </button>
      <button class="floating-btn my-listings-btn" @click="goToMyListings">
        <text class="btn-text">我发布的</text>
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { listingAPI, utils } from '@/utils/api.js'
import { getProvinces, getCitiesByProvince } from '@/utils/areaData.js'
import CreditChecker from '@/utils/creditChecker.js'

// 响应式数据
const listings = ref([])
const isLoading = ref(false)
const hasMore = ref(true)
const searchKeyword = ref('')

// 分页参数
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 筛选参数
const listingTypes = ['全部类型', '公司', '个体户', '代账户']
const selectedTypeIndex = ref(0)

// 省市二级联动筛选
const provinces = ref(['全部省份', ...getProvinces()])
const selectedProvinceIndex = ref(0)

const cities = ref(['全部城市'])
const selectedCityIndex = ref(0)

// 生命周期
onMounted(() => {
  loadListings()
})

// 方法定义
const loadListings = async (isRefresh = false) => {
  if (isLoading.value) return
  
  try {
    isLoading.value = true
    
    if (isRefresh) {
      pagination.page = 1
      hasMore.value = true
    }
    
    // 构建查询参数
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      status: '在售'
    }
    
    // 添加筛选条件
    if (selectedTypeIndex.value > 0) {
      params.listing_type = listingTypes[selectedTypeIndex.value]
    }

    // 省份筛选
    if (selectedProvinceIndex.value > 0) {
      params.registration_province = provinces.value[selectedProvinceIndex.value]
    }

    // 城市筛选
    if (selectedCityIndex.value > 0) {
      params.registration_city = cities.value[selectedCityIndex.value]
    }

    // 添加调试信息
    console.log('加载列表参数:', {
      params,
      selectedProvinceIndex: selectedProvinceIndex.value,
      selectedCityIndex: selectedCityIndex.value,
      isRefresh
    })
    
    if (searchKeyword.value.trim()) {
      params.search = searchKeyword.value.trim()
    }
    
    const response = await listingAPI.getListings(params)
    
    if (response.success) {
      const newListings = response.data || []
      
      if (isRefresh) {
        listings.value = newListings
      } else {
        listings.value = [...listings.value, ...newListings]
      }
      
      // 更新分页信息
      if (response.pagination) {
        pagination.total = response.pagination.total
        hasMore.value = pagination.page < response.pagination.totalPages
      }
    }
    
  } catch (error) {
    utils.handleError(error, '获取列表失败')
  } finally {
    isLoading.value = false
  }
}

const loadMore = () => {
  if (!hasMore.value || isLoading.value) return
  
  pagination.page++
  loadListings()
}

const handleRefresh = () => {
  if (isLoading.value) return
  loadListings(true)
}

const handleSearch = () => {
  loadListings(true)
}

const onTypeChange = (e) => {
  selectedTypeIndex.value = e.detail.value
  loadListings(true)
}

const onProvinceChange = (e) => {
  selectedProvinceIndex.value = e.detail.value

  // 重置城市选择
  selectedCityIndex.value = 0

  // 更新城市列表
  if (e.detail.value === 0) {
    // 选择了"全部省份"
    cities.value = ['全部城市']
  } else {
    // 选择了具体省份
    const selectedProvince = provinces.value[e.detail.value]
    const provinceCities = getCitiesByProvince(selectedProvince)
    cities.value = ['全部城市', ...provinceCities]
  }

  // 添加调试信息
  console.log('省份切换:', {
    selectedIndex: e.detail.value,
    selectedProvince: provinces.value[e.detail.value],
    citiesCount: cities.value.length
  })

  loadListings(true)
}

const onCityChange = (e) => {
  selectedCityIndex.value = e.detail.value
  loadListings(true)
}

const goToDetail = (id) => {
  uni.navigateTo({
    url: `/pages/listings/detail?id=${id}`
  })
}

const goToPublish = async () => {
  const hasCredit = await CreditChecker.checkPublishingCredit({
    fromPage: '/pages/listings/publish',
    action: '发布信息'
  })
  if (!hasCredit) {
    return
  }
  uni.navigateTo({
    url: '/pages/listings/publish'
  })
}

const goToMyListings = () => {
  uni.navigateTo({
    url: '/pages/user/my-listings'
  })
}

// 工具方法
const getStatusClass = (status) => {
  const classMap = {
    '在售': 'status-selling',
    '已售': 'status-sold',
    '下架': 'status-offline'
  }
  return classMap[status] || 'status-default'
}

const formatLocation = (item) => {
  const province = item.registration_province || ''
  const city = item.registration_city || ''

  if (!province && !city) {
    return '未填写'
  }

  if (province && city) {
    // 如果省份和城市相同（如北京市、上海市等直辖市），只显示一个
    if (province === city || city.includes(province.replace('市', '').replace('省', '').replace('自治区', ''))) {
      return province
    }
    return `${province} ${city}`
  }

  return province || city
}

const formatDate = (dateStr) => {
  if (!dateStr) return '未填写'
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return `${year}年${month}月${day}日`
}

const formatTime = (timeStr) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now - date

  if (diff < 24 * 60 * 60 * 1000) {
    return '今天'
  } else if (diff < 7 * 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`
  } else {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    return `${year}年${month}月${day}日`
  }
}

const formatPrice = (price) => {
  if (!price) return '0'
  return Number(price).toLocaleString('zh-CN')
}
</script>

<style scoped>
.listings-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.search-filter-section {
  background: white;
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.search-box {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.search-input {
  flex: 1;
  height: 70rpx;
  padding: 0 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 35rpx;
  font-size: 28rpx;
  margin-right: 20rpx;
}

.search-btn {
  height: 70rpx;
  padding: 0 30rpx;
  background: #22c55e;
  color: white;
  border: none;
  border-radius: 35rpx;
  font-size: 28rpx;
  margin-right: 10rpx;
}

.refresh-btn {
  height: 70rpx;
  width: 70rpx;
  background: #f0f0f0;
  color: #666;
  border: 1rpx solid #ddd;
  border-radius: 35rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
}

.refresh-btn:disabled {
  opacity: 0.5;
}

.refresh-icon {
  font-size: 32rpx;
  font-weight: bold;
}

.filter-row {
  display: flex;
  gap: 15rpx;
  flex-wrap: wrap;
}

.filter-picker {
  flex: 1;
  min-width: 200rpx;
  height: 60rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
}

.picker-text {
  font-size: 26rpx;
  color: #333;
}

.listings-scroll {
  flex: 1;
}

.listings-list {
  padding: 20rpx;
}

.listing-item {
  background: white;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
}

.listing-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.company-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
}

.status-tag {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  color: white;
}

.status-selling {
  background: #22c55e;
}

.status-sold {
  background: #ef4444;
}

.status-offline {
  background: #6b7280;
}

.listing-info {
  margin-bottom: 20rpx;
}

.info-row {
  display: flex;
  margin-bottom: 10rpx;
  font-size: 26rpx;
}

.label {
  color: #666;
  width: 140rpx;
}

.value {
  color: #333;
  flex: 1;
}

.listing-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  font-size: 30rpx;
  font-weight: bold;
  color: #ef4444;
}

.price.negotiable {
  color: #f59e0b;
}

.publish-time {
  font-size: 22rpx;
  color: #999;
}

.loading-section,
.no-more-section,
.empty-section {
  padding: 40rpx;
  text-align: center;
}

.loading-text,
.no-more-text,
.empty-text {
  font-size: 26rpx;
  color: #999;
}

/* 悬浮按钮样式 */
.floating-buttons {
  position: fixed;
  bottom: 40rpx;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  flex-direction: row;
  gap: 30rpx;
  z-index: 999;
}

.floating-btn {
  width: 160rpx;
  height: 80rpx;
  border-radius: 40rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
  font-size: 26rpx;
  font-weight: bold;
  transition: all 0.3s ease;
}

.floating-btn:active {
  transform: scale(0.95);
}

.publish-btn {
  background: linear-gradient(135deg, #22c55e, #16a34a);
  color: white;
}

.my-listings-btn {
  background: linear-gradient(135deg, #3b82f6, #2563eb);
  color: white;
}

.btn-text {
  font-size: 26rpx;
  font-weight: bold;
  color: inherit;
}
</style>
